<template>
  <div class="process">
    <!-- 上部分 -->
    <div class="toper">
      <div class="head">
        <div class="title">简报制作</div>
        <div class="desc">半自动化生成或舆情分析报告<i></i></div>
        <div class="help">通过筛选监测方案、检索和收藏夹导入等多种方式添加素材，一键即可生成专业、详细的数据或舆情分析报告</div>
      </div>
      <div class="liuchen">
        <div class="left">
          <div class="item" v-for="(item,index) in liuchen" :key="index">
            <div class="img"></div>
            <div class="stitle">{{item.title}}</div>
            <div class="desc">{{item.desc}}</div>
          </div>
        </div>
        <div class="right">
          <div class="creat" @click="newbrief()">
            新建简报
          </div>
        </div>
      </div>
      <div class="text">如果您有更专业的简报需求,请点击联系<b @click="goQQ()">人工简报</b>服务</div>
    </div>
    <div class="bodyer">
      <div class="tabs">
        <div class="tab" :class="{active:tabindex==0}" @click="tabindex=0">简报模板</div>
        <div class="tab " :class="{active:tabindex==1}" @click="tabindex=1">简报列表</div>
      </div>
      <div class="views">
        <div class="view" v-show="tabindex==0">
          <div class="item" v-for="(item,index) in tem" :key="index" :class="{active:temindex==index}" @click="temselect(index)">
            <div class="img"></div>
            <div class="title">{{item.title}}</div>
            <div class="desc">{{item.desc}}</div>
          </div>
        </div>
        <div class="view1" v-show="tabindex==1">
          <div class="head">
            <div class="search">
              <input type="text" v-model="briefvalue">
              <!-- <span @click="querylist()" @keyup.enter="querylist()"></span> -->
            </div>
            <el-date-picker
            style="margin-right:0;margin-left:35px"
              v-model="timerange[0]"
              type="datetime"
              :picker-options="pickerBeginDateafter"
              placeholder="选择日期时间">
            </el-date-picker>
            <div class="gang"></div>
            <el-date-picker
              v-model="timerange[1]"
              type="datetime"
              :picker-options="pickerBeginDateBefore"
              placeholder="选择日期时间">
            </el-date-picker>
            <el-button class="sub" @click="papa()" >确定</el-button>
          </div>
          <div class="lists">
            <div class="list">
              <div class="name">简报</div>
              <div class="time">生成时间</div>
              <div class="edit">操作</div>
            </div>
            <div class="list" v-for="(i,index) in brieflist" :key='index'>
              <div class="name">{{i.briefingName}}</div>
              <div class="time">{{i.createTime}}</div>
              <div class="edit">
                <div class="del" @click="delbrief(i.id)">刪除</div>
                <!-- <div class="email">邮件</div> -->
                <div class="word" @click="getBrieftem(i.id)">WORD</div>
                <!-- <div class="pdf">PDF</div> -->
                <div class="ed" @click="getedit(i.id)">编辑</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div ref='main' style="width: 600px;height: 300px;" v-show="0==1"></div>
  </div>
</template>
<script>
import {throttle} from 'utils'
import Docxtemplater from 'docxtemplater'
import ImageModule from 'docxtemplater-image-module'
import JSZip from 'jszip'
import JSZipUtils from 'jszip-utils'
import saveAs from 'jszip/vendor/FileSaver.js'
import echarts from 'echarts'  
import moment from 'moment'

let liuchen = [{title:'选择素材',desc:'选中信息后添加至素材库'},{title:'确认素材',desc:'确认简报素材,作为简报的内容来源'},
              {title:'选择样式',desc:'提供多种模板供您生成简报'},{title:'生成简报',desc:'可以对简报进行下载、发送、删除'}]
let tem = [{title:'网宣版',desc:'适合各地网宣部简报模板'},{title:'党政版',desc:'五角星报头,适合政府及单位的简报模板'},
              {title:'摘要版',desc:'纯信息展示,只阅读重点信息的简报模板'},{title:'经典版',desc:'默认推荐的简报模板'}]
export default {
  name:'process',
		data(){
			return{
        liuchen,
        tem,
        temindex:0,
        timerange:[],
        tabindex:0,
        brieflist:[],
        briefvalue:'',
        pickerBeginDateBefore: {
          disabledDate: (time) => {
            let beginDateVal = this.timerange[0];
            if (beginDateVal) {
                return time.getTime() < beginDateVal;
            }
          }
        },
        pickerBeginDateafter: {
          disabledDate: (time) => {
            let afterDateVal = this.timerange[1];
            if (afterDateVal) {
                return time.getTime() > afterDateVal;
            }
          }
        },
			}
    },
    mounted(){
      // this.papa = throttle(1000, this.querylist.bind(this))
      if(this.$route.params.id=='tem'){
        this.tabindex  = 0
      }else{
        this.tabindex = 1
      }
      this.papa()
    },
    methods:{
      getedit(id){
        this.$router.push('/brief/editbrief/'+id)
        
      },
      goQQ(){
        window.open('http://wpa.qq.com/msgrd?v=3&uin=154521048&site=oicqzone.com&menu=yes')
      },
      newbrief(){
        this.$router.push('/brief/step01')
      },
      temselect(index){
        this.temindex = index
        localStorage.temindex = index
      },
      papa: throttle(1000, async function(){
        let s = this.timerange[0]
        if(this.timerange[0]){
          s = moment(this.timerange[0]).format('YYYY-MM-DD HH:mm:ss')
          console.log(true);
        }else{
          s = ''
        }
        let e = this.timerange[1]
        if(this.timerange[1]){
          e = moment(this.timerange[1]).format('YYYY-MM-DD HH:mm:ss')
          console.log(true);
        }else{
          e = ''
        }
        let res = await this.$http.post('vrv-monitor-platform-web/briefing/queryByOrgCode',{
          briefingName:this.briefvalue,
          startQueryTime:s,
          endQueryTime:e
        })
        this.brieflist = res.body.data
      }),
      async delbrief(id){
        let res = await this.$http.post('/vrv-monitor-platform-web/briefing/deleteBriefing',{
          id:id
        })
        if(res.body.success){
          this.$message.success('删除成功')
          this.brieflist = this.brieflist.filter(d => d.id != id )
        }else{
          this.$message.error(res.body.message)
        }
      },
      async getBrieftem(id){
        let loadDocx = path => new Promise(r => JSZipUtils.getBinaryContent(path, (err, d) => r(d)))
        let loadJson = path => fetch(path).then(d => d.json())
        let chart = echarts.init(this.$refs.main)
        let imageModule = new ImageModule({
          centered: false,
          getImage: d => Uint8Array.from(atob(d.slice(22)), c => c.charCodeAt(0)),
          getSize: () => ([400, 200])
        })
        function genChart0(d){
          let option = {
            animation: false,
            tooltip : {
              trigger: 'item',
              formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            series : [{
              name: '访问来源',
              type: 'pie',
              radius : '55%',
              center: ['50%', '60%'],
              data: d,
              itemStyle: {
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }]
          }
          chart.setOption(option)
          return chart.getDataURL()
        }

        function genChart1(d){
          let option = {
            animation: false,
            color: ['#3398DB'],
            tooltip : {
              trigger: 'axis',
              axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis : [{
              type : 'category',
              data : d.map(d => d.name),
              axisTick: {
                alignWithLabel: true
              },
              axisLabel: {
                interval: 0
              }
            }],
            yAxis : [{
              type : 'value'
            }],
            series : [{
              type:'bar',
              barWidth: '60%',
              data: d.map(d => d.value)
            }]
          }
          chart.clear()
          chart.setOption(option)
          return chart.getDataURL()
        }

        Promise.all([
          loadDocx('static/examples/template.docx'),
          this.$http.post('vrv-monitor-platform-web/briefing/queryById',{id:id}).then(function(d){
            console.log(d)
            console.log(d.json())
            return d.json()
          })
        ]).then(([content, jsondata]) => {
          console.log(content)
          let zip = new JSZip(content)
          console.log(zip)
          console.log(imageModule)
          let doc = new Docxtemplater().attachModule(imageModule).loadZip(zip)
          let d = jsondata.data
          let str1 = ''
          let websiteLeader = d.websiteLeader
          function setwebsite(arr){
            let t = arr.reduce((a,d) => a +d.doc_count,0)
            let m = `本报告就加入素材的文章进行分析，共有${t}篇相关素材。`
            arr.forEach(d =>{
              let str = d.websiteName+d.doc_count+'篇,占比'+(d.doc_count/t*100).toFixed(2)+'%,'
              m += str
            });
            m+=`目前主要的报道集中在${websiteLeader}等几大站点。详细报告请继续浏览。`
            str1 = m
          }
          setwebsite(JSON.parse(d.website))
          let arr = JSON.parse(d.sensitivity)
          let t = arr.reduce((a,d) => a +d.doc_count,0)
          let m = arr.filter(d => d.key ==2)[0].doc_count
          let mz = ((m/t)*100).toFixed(2)
          let nm = t - m
          let nmz = ((nm/t)*100).toFixed(2)
          let str2 = `监测主题相关信息${t}条，其中敏感${m}条，敏感占比${mz}%，非敏感${nm}条，非敏感占比${nmz}%`
          doc.setData({
            str1:str2,
            str2:str1,
            date: d.createTime,
            organizationName: d.organizationName,
            suggestion: d.suggestion,
            ...JSON.parse(d.titles),
            infos: JSON.parse(d.importantOpinion).map((d, i) => ({
              num: i + 1,
              title: d.title,
              date: new Date(d.poTime).toISOString().slice(0, 10),
              source: d.source || d.webSite,
              mg: !!d.positiveOrNegative
            })),
            chart32: genChart0(JSON.parse(d.website).map(d => ({name: d.websiteName, value: d.doc_count}))),
            chart33: genChart1(JSON.parse(d.liveness)),
          })
          doc.render()
          let out = doc.getZip().generate({
            type: "blob",
            mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          })
          saveAs(out, `${d.briefingName}.docx`)
        })
      }
    }
}
</script>
<style lang="stylus" scoped>
.gang
  display inline-block 
  width 15px
  height 3px
  background #898989
  margin 0 3px;
  transform translateY(-1.5px)
.process
  .toper
    padding 30px
    background #fff
    >.head
      height 40px
      font-size 0
      border-bottom 1px solid #dcdcdc 
      box-sizing border-box
      .title
        display inline-block
        font-size 1.3rem
        color #555
        font-weight bold
      .desc
        display inline-block
        margin-left 8px
        font-size 0.88rem
        color #999
        i
          display inline-block
          margin-left 8px
          width 14px
          height 14px
          background-image url('img/brief-why.png')
          background-size cover
          background-repeat no-repeat
          vertical-align -3px
          cursor pointer
    .liuchen
      margin-top 36px
      font-size 0
      display flex
      >.left
        flex 1
        font-size 0
        display flex
        .item 
          display inline-block
          width 240px
          .img
            float left
            width 67px
            height 48px
            margin-right 15px
            background-repeat no-repeat
            background-size 100%
        
          &:nth-child(1)
            .img
              background-image url(img/brief-icon-y0.png)
          &:nth-child(2)
            .img
              background-image url(img/brief-icon-y1.png)
          &:nth-child(3)
            .img
              background-image url(img/brief-icon-y2.png)
          &:nth-child(4)
            .img
              background-image url(img/brief-icon-y3.png)
          .stitle
            font-size 20px
            color #333
            line-height 1
          .desc
            margin-top 8px
            width 194px
            font-size 14px
            color #999
            line-height 1.2
      .right
        flex 0 0 150px
        width 150px
        vertical-align top
        float right
        .creat
          float right
          border-radius 8px 
          width 120px
          height  58px
          text-align center
          line-height 58px
          font-size 14px
          color #fff
          background #ea6553 url(img/brief-small-icon.png) no-repeat
          background-position 10% 55%
          padding 0 15px
          box-sizing border-box
          text-indent 20px
          cursor pointer
    .text
      font-size 14px
      color #999
      width 100%
      margin-top 15px
      b
        color #e75a46
        display inline-block
        padding 0 5px
        cursor pointer
  .bodyer
    .tabs
      background #f0f5fb
      height 40px
      padding 14px 30px 0 30px
      border-bottom 1px solid #dcdcdc
      font-size 0
      .tab
        display inline-block
        width 118px
        height 39px
        line-height 40px
        background #fff
        font-size 14px
        color #555
        text-align center
        border-top-right-radius 8px
        border-top-left-radius 8px
        cursor pointer
        &:last-child
          margin-left 8px
        &.active
          border 1px solid #dcdcdc
          border-bottom 1px solid #fff
          color #ec6941
          font-weight bold
    .views
      background #fff
      .view
        padding 20px 30px
        font-size 0
        .item
          position relative
          display inline-block
          width 260px
          height 245px
          margin-right 28px
          border 1px solid #dcdcdc
          border-radius 5px
          overflow hidden
          cursor pointer
          margin-bottom 28px
          &.active
            border-color #e75a46
            &:after
              position absolute
              top 0
              right 0
              display block
              content "默认"
              height 28px
              line-height 28px
              width 200px
              background #e75246
              color #fff
              font-size 14px
              text-align center
              transform rotate(45deg) translatex(61px) translateY(-40px)
          >.img
            height 155px
            background url(img/templet.png) no-repeat
            background-size 105%
          .title
            font-size 20px
            color #333
            padding-left 35px
            margin-top 18px
          .desc
            margin-top 18px
            padding-left 35px
            font-size 12px
            color #666
      .head
        padding 10px 30px
        .search
          position relative
          float left
          border 1px solid #dcdcdc
          width 240px
          height 35px
          border-radius 50px
          padding 0 30px
          overflow hidden
          box-sizing border-box
          margin-top 3px
          >input 
            border 0
            height 100%
            width 100%
            outline none
          >span 
            position absolute
            top 8px
            right 11px
            width 16px
            height 16px
            background url('img/brief-search.png')
            background-size 100%
            cursor pointer
        .sub
          width 90px
          margin-left 8px
  .lists
    .list
      display flex
      height 60px
      border-top 1px solid #dcdcdc
      font-size 14px
      color #000
      line-height 60px
      text-align center
      box-sizing border-box
      &.first-of-type
        color #535353
      .name
        flex 1
      .time
        flex 1
      .edit
        width 400px
        flex 0 0 400px
        border-left 1px solid #dcdcdc 
        font-size 0
        >div
          display inline-block
          vertical-align top
          height 16px
          line-height 1.2
          color #384182
          font-size 14px
          text-indent 20px
          margin-right 30px
          margin-top 22px
          cursor pointer
          &:last-child
            margin-right 0
          &.del
            background url(img/brief-list-del.png) no-repeat
            background-size 15px 16px
          &.email
            background url(img/brief-list-email.png) no-repeat
            background-size 16px 13px
            background-position 0 2px
          &.word
            background url(img/brief-list-word.png) no-repeat
            background-size 14px 16px
            line-height 1.2
          &.pdf
            background url(img/brief-list-pdf.png) no-repeat
            background-size 14px 16px
            line-height 1.2
          &.ed
            background url(img/brief-list-edit.png) no-repeat
            background-size 16px 16px

@media screen and (max-width: 1500px) 
  .process 
    .toper 
      .text
        font-size 12px
      .liuchen 
        >.left 
          .item
            width 210px
            .img
              width 57px
              height 41px
            .stitle
              font-size 16px
            .desc
              font-size 12px
        .right
          .creat
            width 100px
            height 45px
            font-size 12px
            line-height 45px
            background-size 20px 27px

    .bodyer 
      .views 
        .view 
          .item
            width 220px
            height 207px
            >.img
              height 130px
            .title
              font-size 16px
              margin-top 10px
            .desc
              margin-top 10px
              font-size 12px
      .lists
        .list
          height 45px
          line-height 45px
          font-size 12px
          .edit 
            >div
              margin-top 15px
              font-size 12px

    


</style>

